package com.yikome.order.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.base.Preconditions;
import com.itmuch.lightsecurity.annotation.PreAuthorize;
import com.yikome.constant.CommonConstant;
import com.yikome.order.dto.OrderDTO;
import com.yikome.order.dto.OrderSkuDTO;
import com.yikome.order.entity.Order;
import com.yikome.order.entity.OrderAddress;
import com.yikome.order.entity.OrderProduct;
import com.yikome.order.exportDTO.ExportOrderDTO;
import com.yikome.order.mq.request.OrderToAdminRequest;
import com.yikome.order.request.OrderRequest;
import com.yikome.order.service.OrderService;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;

@RestController
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private OrderService orderService; 
	
	@PutMapping("/api/status")
	public Boolean changeStatus(@RequestBody Map<String, Object> params) {
		
		String orderCode = Convert.toStr(params.get("orderCode"));
		Integer orderStatus = Convert.toInt(params.get("orderStatus"));
		
		orderService.changeStatus(orderCode, orderStatus);
		
		return Boolean.TRUE;
	}
	
	
	@GetMapping("/list")
	@PreAuthorize("hasAnyRoles('admin','analysis', 'finance', 'order', 'shop', 'affiliate')")
	public Page<OrderDTO> findOrder(OrderRequest orderRequest , @PageableDefault(sort = {"o_order.id"}, direction = Sort.Direction.DESC)Pageable pageable){
		return orderService.findOrder(orderRequest, pageable);
	}
	
	@GetMapping("/{orderCode}/products")
	@PreAuthorize("hasAnyRoles('admin','analysis', 'finance', 'order', 'shop', 'affiliate')")
	public List<OrderSkuDTO> findOrderProduct(@PathVariable("orderCode") String orderCode){
		return orderService.findOrderProduct(orderCode);
	}
	
	/**
	 * remark | status | price
	 */
	@PutMapping
	@PreAuthorize("hasAnyRoles('admin', 'order', 'shop')")
	public Order editOrder(@RequestBody Order order) {
		Preconditions.checkArgument(order.getId() != null, "ID参数信息不存在...");
		return orderService.editOrder(order);
	}
	
	/**
	 * consignee | tel | city | district | details
	 */
	@PutMapping("/address")
	@PreAuthorize("hasAnyRoles('admin', 'order', 'shop')")
	public OrderAddress editOrderAddress(@RequestBody OrderAddress orderAddress) {
		Preconditions.checkArgument(orderAddress.getId() != null, "ID参数信息不存在...");
		return orderService.editOrderAddress(orderAddress);
	}
	
	/**
	 * productPrice | quantity
	 */
	@PutMapping("/product")
	@PreAuthorize("hasAnyRoles('admin', 'order', 'shop')")
	public OrderProduct editOrderProduct(@RequestBody OrderProduct orderProduct) {
		Preconditions.checkArgument(orderProduct.getId() != null, "ID参数信息不存在...");
		Preconditions.checkArgument(orderProduct.getProductPrice().doubleValue() > 0, "价格参数信息不存在...");
		Preconditions.checkArgument(orderProduct.getQuantity() > 0, "数量参数信息不存在...");
		return orderService.editOrderProduct(orderProduct);
	}
	
	@GetMapping("/whole/export")
	@PreAuthorize("hasAnyRoles('admin', 'order', 'shop')")
	public String exportWholeOrder(OrderRequest orderRequest) throws IOException {
		
		List<ExportOrderDTO> exportOrderDTOs = orderService.findExportWholeOrder(orderRequest);
		
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("订单明细", "订单明细"), ExportOrderDTO.class, exportOrderDTOs);
        
    	String folderPath = CommonConstant.BASE_LOCATION + LocalDateTime.now(ZoneId.of("+8")).format(CommonConstant.DATETIMEFORMATTRT_DATE) + '/' ;
		File fileFolder = new File(folderPath);
		if (!fileFolder.exists())fileFolder.mkdirs();
		
		String fileName = LocalDateTime.now(ZoneId.of("+8")).format(CommonConstant.DATETIMEFORMATTRT_TIME) + "-订单完整版.xlsx" ;
		
		String filePath = folderPath + fileName ;
		FileOutputStream fos = new FileOutputStream(filePath);
		workbook.write(fos);
        fos.close();
		return filePath ;
	}
	
	@DeleteMapping("/{orderCode}")
	@PreAuthorize("hasAnyRoles('admin', 'order', 'shop')")
	public Boolean deleteOrder(@PathVariable("orderCode") String orderCode) {
		orderService.deleteOrder(orderCode);
		
		return Boolean.TRUE;
	}
}
